package com.qu.waibao.publisher;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;
import com.qu.waibao.AppConfig;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.baidu.MapActivity;
import com.qu.waibao.base.BaseFragment;
import com.qu.waibao.bean.InitService;
import com.qu.waibao.bean.PayResult;
import com.qu.waibao.home.activity.PublishActivity;
import com.qu.waibao.home.activity.ShopActivity;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.my.activity.HelpActivity;
import com.qu.waibao.my.activity.PublishOrderActivity;
import com.qu.waibao.my.adapter.GridImageAdapter;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.AppOperator;
import com.qu.waibao.network.HttpModeBase;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.GsonUtil;
import com.qu.waibao.utils.PayUitl;
import com.qu.waibao.utils.TDevice;
import com.qu.waibao.utils.ToastUtil;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import info.wangchen.simplehud.SimpleHUD;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2018/7/21.
 */

public class PublisherFragment extends BaseFragment implements View.OnClickListener{
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.et_address)
    EditText et_address;
    @BindView(R.id.et_linkman)
    EditText et_linkman;
    @BindView(R.id.et_linktel)
    EditText et_linktel;
    @BindView(R.id.tv_feed)
    EditText tv_feed;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_show_time)
    TextView tv_show_time;
    @BindView(R.id.et_remark)
    EditText et_remark;
    @BindView(R.id.ll_payment)
    LinearLayout ll_payment;
    @BindView(R.id.tv_ding)
    TextView tv_ding;
    private GridImageAdapter imageAdapter;
    private OptionsPickerView timePickView;
    private String province = "";
    private String city = "";
    private String area = "";
    private String longitude = "";
    private String latitude = "";
    private String indate = "";
    private String servicecategoryid = "";
    private String serviceid = "";
    private HttpModeBase httpModeBase;
    private boolean isPayment = false;
    private String paytype = "";
    private boolean isLanchActivty = false;
    private List<LocalMedia> list;
    private IWXAPI api;//微信支付参数
    private StringBuilder builder = new StringBuilder();
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case HttpModeBase.HTTP_SUCCESS:
                    String result = (String) msg.obj;
                    int position = msg.arg2;
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if(jsonObject.optInt("status") == 1){
                            String url = jsonObject.optString("src");
                            imageAdapter.addItem(url);
                            if(position < list.size() -1) {
                                position++;
                                imageSaveSet(list.get(position).getCompressPath(), position);
                            }
                        }else {
                            imageSaveSet(imageAdapter.getItems().get(position),position);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case HttpModeBase.HTTP_ERROR:
                    SimpleHUD.dismiss();
                    break;
            }
        }
    };
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.equals("com.qu.waibao.PAYMENTSUCCESS")){
                isLanchActivty = true;
                startActivity(new Intent(mContext,PublishOrderActivity.class));
            }
        }
    };
    @Override
    protected int getLayoutId() {
        return R.layout.activity_publish;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        tv_title.setText("发布");
        iv_publish.setVisibility(View.GONE);
        ll_back.setVisibility(View.GONE);
        httpModeBase = new HttpModeBase(handler,getActivity());
        if(LocationUtils.Mylocation != null){
            province = LocationUtils.Mylocation.getProvince();
            city = LocationUtils.Mylocation.getCity();
            area = LocationUtils.Mylocation.getDistrict();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.qu.waibao.PAYMENTSUCCESS");
        getActivity().registerReceiver(receiver,intentFilter);
    }

    @Override
    public void onResume() {
        super.onResume();
        if(isLanchActivty) {
            tv_name.setText("");
            tv_ding.setText("");
            et_address.setText("");
            et_linkman.setText("");
            tv_show_time.setText("");
            et_linktel.setText("");
            tv_feed.setText("");
            et_remark.setText("");
            imageAdapter.clear();
            servicecategoryid = "";
            indate = "";
        }
    }

    @Override
    protected void initData() {
        super.initData();
        //图片
        imageAdapter = new GridImageAdapter(getActivity(), new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                if(ContextCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                    openPhotos();
                }else {
                    Toast.makeText(getActivity(),"没有SD卡的权限",Toast.LENGTH_SHORT).show();
                }
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),4);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(imageAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 图片选择结果回调
                list = PictureSelector.obtainMultipleResult(data);
                if(list != null){
                    imageSaveSet(list.get(0).getCompressPath(),0);
                }
            }else if(requestCode == 0){
                latitude = String.valueOf(data.getDoubleExtra("latitude",0));
                longitude = String.valueOf(data.getDoubleExtra("longitude",0));
                String address = data.getStringExtra("address");
                et_address.setText(address);
                if(LocationUtils.Mylocation != null){
                    tv_ding.setText(LocationUtils.Mylocation.getProvince()
                            +LocationUtils.Mylocation.getCity()+LocationUtils.Mylocation.getDistrict());
                }
            }else if(requestCode == 1){
                InitService initService = (InitService) data.getExtras().getSerializable("InitService");
                servicecategoryid = initService.getServicecategoryid();
                et_remark.setHint(initService.getRemarktxt());
                tv_name.setText(initService.getServicecategoryname());
                if(initService.getIfneedpay().equals("0")){
                    ll_payment.setVisibility(View.GONE);
                }else {
                    ll_payment.setVisibility(View.VISIBLE);
                    isPayment = true;
                }
            }
        }
    }

    /**
     * 打开相册
     */
    public void openPhotos() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(3)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .isGif(false)// 是否显示gif图片
                .compress(true)// 是否压缩 true or false
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @OnClick({R.id.rl_select_type,R.id.rl_location,R.id.tv_publish,R.id.ll_time,R.id.tv_shuoming})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_shuoming:
                startActivityForResult(new Intent(mContext,HelpActivity.class),1);
                break;
            case R.id.rl_select_type:
                isLanchActivty = false;
                startActivityForResult(new Intent(mContext,InitServiceActivity.class),1);
                break;
            case R.id.rl_location:
                isLanchActivty = false;
                startActivityForResult(new Intent(getActivity(), MapActivity.class),0);
                break;
            case R.id.ll_time: //时间选择
                TDevice.closeKeyboard(et_linkman);
                initTime();
                timePickView.show();
                break;
            case R.id.tv_publish:
                String address = et_address.getText().toString();
                String linkman = et_linkman.getText().toString();
                String linktel = et_linktel.getText().toString();
                String remark = et_remark.getText().toString();
                String moneypay_online = tv_feed.getText().toString();
                String images = getImages();
                if(TextUtils.isEmpty(servicecategoryid)){
                    ToastUtil.show(getActivity(),"请选择发布的类型");
                    return;
                }else if(TextUtils.isEmpty(address)){
                    ToastUtil.show(getActivity(),"请选择详细地址");
                    return;
                }else if(TextUtils.isEmpty(linkman)){
                    ToastUtil.show(getActivity(),"请输入联系人");
                    return;
                }else if(TextUtils.isEmpty(indate)){
                    ToastUtil.show(getActivity(),"请选择服务时间");
                    return;
                }else if(TextUtils.isEmpty(linktel)){
                    ToastUtil.show(getActivity(),"请输入联系电话");
                    return;
                }else if(TextUtils.isEmpty(remark)){
                    ToastUtil.show(getActivity(),"请输入您的需求");
                    return;
                }
                submit(images,address,linkman,linktel,remark,moneypay_online);
                break;
        }
    }
    private String getImages(){
        StringBuilder builder = new StringBuilder();
        String uploadImages = "";
        if(imageAdapter != null){
            for(int i = 0;i<imageAdapter.getItems().size();i++){
                builder.append(imageAdapter.getItems().get(i)).append(",");
            }
            String images = builder.toString();
            if(!TextUtils.isEmpty(images)){
                uploadImages = images.substring(0,images.length()-1);
            }
        }
        return uploadImages;
    }
    public void submit(String imgs,String address,String linkman,String linktel,String remark,String moneypay_online){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.service_set);
        map.put("serviceid",serviceid);
        map.put("userid", AppConfig.getString("userid"));
        map.put("servicecategoryid",servicecategoryid);
        map.put("province",province);
        map.put("city",city);
        map.put("area",area);
        map.put("address",address);
        map.put("longitude",longitude);
        map.put("latitude",latitude);
        map.put("linkman",linkman);
        map.put("linkphone",linktel);
        map.put("indate",indate);
        map.put("imgs",imgs);
        map.put("remark",remark);
        map.put("moneypay_online",moneypay_online);
        RequestParams params = NetManager.getUrl(map);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if(jsonObject.optInt("status") == 1){
                         if(isPayment){
                             String ordercode = jsonObject.optString("ordercode");
                             paymentDialog(ordercode,tv_feed.getText().toString().trim());
                         }else {
                             isLanchActivty = true;
                             ToastUtil.show(getActivity(),jsonObject.optString("message"));
                             Intent intent = new Intent(getActivity(), PublishOrderActivity.class);
                             intent.putExtra("type","qiang");
                             startActivity(intent);
                         }
                    }else {
                        ToastUtil.show(getActivity(),jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                SimpleHUD.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                SimpleHUD.dismiss();
            }

            @Override
            public void onFinished() {
                SimpleHUD.dismiss();
            }
        });
    }

    public void imageSaveSet(String path,int position){
        httpModeBase.xutilsPostList(NetManager.BaseUrl,NetManager.image_save_set(),path,position,
                false);
    }

    public void initTime(){
        timePickView = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String date = getList().get(options1);
                if(date.equals("30分钟")){
                    indate = "30";
                }else if(date.equals("2小时")){
                    indate = "120";
                }else if(date.equals("8小时")){
                    indate = "480";
                }else if(date.equals("24小时")){
                    indate = "1440";
                }
                tv_show_time.setText(date);
            }
        }).setLayoutRes(R.layout.select_time_dialog, new CustomListener() {
            @Override
            public void customLayout(View v) {
                TextView tv_cancel = v.findViewById(R.id.tv_cancel);
                TextView tv_sure = v.findViewById(R.id.tv_sure);
                final EditText et_time = v.findViewById(R.id.et_time);
                tv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        timePickView.dismiss();
                    }
                });
                tv_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        TDevice.closeKeyboard(et_time);
                        String time = et_time.getText().toString().trim();
                        if(!TextUtils.isEmpty(time)) {
                            tv_show_time.setText(time + "天");
                            int day = Integer.valueOf(time);
                            indate = String.valueOf(day * 1440);
                        }else {
                            timePickView.returnData();
                        }
                        timePickView.dismiss();
                    }
                });
            }
        })
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setTitleText("时间选择")//标题
                .setSubCalSize(14)//确定和取消文字大小
                .setTitleSize(16)//标题文字大小
                .setTitleColor(Color.parseColor("#333333"))//标题文字颜色
                .setSubmitColor(Color.parseColor("#f29f1b"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#f29f1b"))//取消按钮文字颜色
                .setTitleBgColor(Color.parseColor("#F1F1F1"))//标题背景颜色 Night mode
                .setBgColor(Color.parseColor("#FFFFFF"))//滚轮背景颜色 Night mode
                .setContentTextSize(18)//滚轮文字大小
                .setOutSideCancelable(true)
                .isDialog(true)//是否显示为对话框样式
                .build();//点击外部dismiss default true
        timePickView.setPicker(getList());
    }

    public List<String> getList(){
        List<String> list = new ArrayList<>();
        list.add("30分钟");
        list.add("2小时");
        list.add("8小时");
        list.add("24小时");
        return list;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler = null;
        httpModeBase = null;
        builder = null;
        if(receiver != null){
            getActivity().unregisterReceiver(receiver);
            receiver = null;
        }
    }
   public void paymentDialog(final String ordercode, final String price){
       NiceDialog.init()
               .setLayoutId(R.layout.zhifu_dialog_layout)     //设置dialog布局文件
               .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                   @Override
                   public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                       TextView textView = holder.getView(R.id.tv_tv_title);
                       textView.setText("支付金额"+price);
                       final TextView tv_weixin = holder.getView(R.id.tv_weixin);
                       final TextView tv_zhifubao = holder.getView(R.id.tv_tv_zhifubao);

                       holder.setOnClickListener(R.id.ll_weixin, new View.OnClickListener() {
                           @Override
                           public void onClick(View v) {
                               tv_weixin.setTextColor(Color.parseColor("#67b8f2"));
                               tv_zhifubao.setTextColor(Color.parseColor("#333333"));
                               paytype = "微信支付";
                           }
                       });

                       holder.setOnClickListener(R.id.ll_zhifubao, new View.OnClickListener() {
                           @Override
                           public void onClick(View v) {
                               tv_weixin.setTextColor(Color.parseColor("#333333"));
                               tv_zhifubao.setTextColor(Color.parseColor("#67b8f2"));
                               paytype = "支付宝支付";
                           }
                       });
                       holder.setOnClickListener(R.id.tv_tv_sure, new View.OnClickListener() {
                           @Override
                           public void onClick(View v) {
                               dialog.dismiss();
                               getOrderCode(ordercode,paytype);
                           }
                       });
                       holder.setOnClickListener(R.id.iv_delete, new View.OnClickListener() {
                           @Override
                           public void onClick(View v) {
                               dialog.dismiss();
                           }
                       });

                   }
               })
               .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
               .setShowBottom(true)     //是否在底部显示dialog，默认flase
               .setOutCancel(true)     //点击dialog外是否可取消，默认true
               .show(getChildFragmentManager());     //显示dialog
   }
    public void getOrderCode(String ordercode, final String paytype){
        SimpleHUD.showLoadingMessage(getActivity(),"",AppConfig.isCanCancel);
        final Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.order_pay_set);
        map.put("ordercode",ordercode);
        map.put("paytype",paytype);
        RequestParams params = NetManager.getUrl(map);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if(jsonObject.optInt("status") == 1) {
                        if (paytype.equals("微信支付")) {
                            String optString = jsonObject.optString("prepayinfo");
                            JSONObject payObj = new JSONObject(optString);
                            doWeiXinPay(payObj.optString("appid"), payObj.optString("partnerid"), payObj.optString("prepayid"), payObj.optString("noncestr"),
                                    payObj.optString("timestamp"), payObj.optString("package"), payObj.optString("sign"));
                        } else {
                            JSONObject payObj = jsonObject.optJSONObject("prepayinfo");
                            doAlipay("车捷派服务", "车捷派服务", payObj.optString("OrderCode"),
                                    payObj.optString("url_notify"), payObj.optString("partner"),
                                    payObj.optString("seller"), payObj.optString("private_key"));
                        }
                    }else {
                        ToastUtil.show(mContext,jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                SimpleHUD.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                SimpleHUD.dismiss();
            }

            @Override
            public void onFinished() {
                SimpleHUD.dismiss();
            }
        });
    }
    public void doWeiXinPay(String appId, String partnerId, String prepayId, String nonceStr,
                            String timeStamp,String packageValue, String sign) {
        SimpleHUD.dismiss();
        api = WXAPIFactory.createWXAPI(getActivity(),null);
        api.registerApp(appId);
        PayReq req = new PayReq();
        req.appId			= appId;
        req.partnerId		= partnerId;
        req.prepayId		= prepayId;
        req.nonceStr		= nonceStr;
        req.timeStamp		= timeStamp;
        req.packageValue	= packageValue;
        req.sign			= sign;
        api.sendReq(req);
    }
    public void doAlipay(String subject,String body,String out_trade_no,String notify_url,String partner
            ,String seller,String private_key) {
        // 订单
        String orderInfo = PayUitl.getOrderInfo(subject,body,out_trade_no, notify_url, "0.01",partner,seller);
        // 对订单做RSA 签名
        String sign = PayUitl.sign(orderInfo,private_key);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + PayUitl.getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                SimpleHUD.dismiss();
                PayTask alipay = new PayTask(getActivity());
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo,true);
                PayResult payResult = new PayResult(result);
                final String resultStatus = payResult.getResultStatus();
                AppOperator.runOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000")) {
                            ToastUtil.show(mContext, "支付成功");
                            startActivity(new Intent(mContext,PublishOrderActivity.class));
                            getActivity().finish();
                        }else if (TextUtils.equals(resultStatus, "8000")) {
                            // 判断resultStatus 为非“9000”则代表可能支付失败
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            ToastUtil.show(mContext, "支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            ToastUtil.show(mContext, "支付失败");
                        }
                    }
                });
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}
